import React, { Component } from 'react'
//引入action对象
import {
    increment,
    decrement,
    incrementAsync
} from '../../redux/actions/count'
//引入connect用于连接UI组件与redux
import { connect } from 'react-redux'

//定义UI组件
class Count extends Component {
    state = {
        carName: 'BMW'
    }

    //加法
    handleIncrement = () => {
        let { value } = this.selectNumber
        this.props.increment(value * 1)
    }
    //减法
    handleDecrement = () => {
        let { value } = this.selectNumber
        this.props.decrement(value * 1)
    }
    //奇数加
    handleIncrementIfOdd = () => {
        let { value } = this.selectNumber
        if (this.props.count % 2 == 1) {
            this.props.increment(value * 1)
        }
    }
    //异步加
    handleIncrementAsync = () => {
        let { value } = this.selectNumber
        this.props.incrementAsync(value * 1, 500)
    }
    render() {
        let { } = this.props
        return (
            <div>
                <h2>我是Count组件,下方组件总人数为:{this.props.numberOfPeople}</h2>
                <h4>当前求和为:{this.props.count}</h4>
                <select ref={c => this.selectNumber = c}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>&nbsp;
                <button onClick={this.handleIncrement}>+</button>&nbsp;
                <button onClick={this.handleDecrement}>-</button>&nbsp;
                <button onClick={this.handleIncrementIfOdd}>当前求和为奇数再加</button>&nbsp;
                <button onClick={this.handleIncrementAsync}>异步加</button>
            </div>
        )
    }
}

//使用connect()()创建并暴露一个Count的容器组件
export default connect(
    //mapStateToProps
    state => ({ count: state.gentles, numberOfPeople: state.persons.length }),

    //mapDispatchToProps的简写
    {
        increment,
        decrement,
        incrementAsync
    }
)
    (Count)